package com.hk.aop;

import com.hk.annotation.AutoCheck;
import com.hk.enums.UserRoleEnum;
import com.hk.exception.BusinessException;
import com.hk.exception.ErrorCode;
import com.hk.exception.ThrowExceptionUtil;
import com.hk.model.vo.user.UserVO;
import com.hk.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;

/**
 * @author huangkun
 * @date 2024/12/12 20:42
 */
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;

    @Around("@annotation(autoCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AutoCheck autoCheck) throws Throwable {
        String mustRole = autoCheck.mustRole();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        UserVO user = userService.getCurrentUser(requestAttributes.getRequest());
        UserRoleEnum roleEnum = UserRoleEnum.getEnumByValue(mustRole);
        if (roleEnum == null) {
            return joinPoint.proceed();
        }
        //校验当前用户的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByCode(user.getRole());
        ThrowExceptionUtil.throwIf(userRoleEnum == null, ErrorCode.NO_PERMISSION);

        //校验接口权限
        if (mustRole.equals(userRoleEnum.getValue()) || userRoleEnum.getValue().equals(UserRoleEnum.ADMIN.getValue())) {
            return joinPoint.proceed();
        }
        throw new BusinessException(ErrorCode.NO_PERMISSION);
    }
}
